package org.example.core.utils;

import net.sf.oval.ConstraintViolation;
import net.sf.oval.Validator;
import org.example.core.exception.BusinessException;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 参数校验工具类
 * author Calvin
 */
public class VerifyUtil {

    /**
     * 私有构造方法
     */
    private VerifyUtil() {}

    private static final Validator VALIDATOR = new Validator();

    /**
     * 请求参数非空、格式验证，请求对象
     * @param object                  请求校验参数
     * @throws BusinessException           业务异常
     */
    public static void validateObject(Object object) {
        List<ConstraintViolation> list = VALIDATOR.validate(object);
        if (!CollectionUtils.isEmpty(list)) {
            throw new BusinessException(list.get(0).getMessage());
        }
    }

    /**
     * 集合对象校验
     *
     * @param objects list集合
     */
    public static void verifyList(Object... objects) {
        for (Object object : objects) {
            if (object instanceof List<?>) {
                List<?> list = (List<?>) object;
                if (CollectionUtils.isEmpty(list)) {
                    continue;
                }
                for (Object request : list) {
                    validateObject(request);
                }
            }
        }
    }
}